<?php
/**
 * 上传(修改)头像
 * ModifyImage 
 */
    class ModifyImage extends APIBase {
		
		public $tag = "ModifyImage";
		
		public function before() {
			$this->initMysql();
			$this->initCacheRedis();
			return true;
		}
		
		public function logic() {
			$isExists = $this->data_redis->exists("hu:{$this->uid}");
			if (!$isExists) {
				return;
			}

			$rdate = date("Y-m-d-H-i-s",time());
			$fileName = $rdate . "_{$this->uid}" . ".jpg";
			$this->data_redis->hSet("hu:{$this->uid}", "avater", $fileName);
			$rdate = date("Y-m-d",time());
			$pieces = explode("-",$rdate);
			$path = 'image' ."/".$pieces[0]."/".$pieces[1]."/".$pieces[2];
			$this->create_dir($path);
			$fileName = $path . "/" . $fileName;
			$photo = file_get_contents("php://input") ? file_get_contents("php://input") : gzuncompress($GLOBALS['HTTP_RAW_POST_DATA']);
			file_put_contents($fileName, $photo);
			$data = array();
			$data['avater_url'] = "http://" . $_SERVER["SERVER_ADDR"] . "/" ."zjhapi/" . $fileName;

			//删除前面的图片资源
			$old_avater_url = $this->data_redis->hget("hu:{$this->uid}","avater_url");
			$substr = strstr($old_avater_url,"zjhapi/image");
			if ($substr) 
			{
				$old_res_pathfile = $_SERVER['DOCUMENT_ROOT']. "/" . $substr;
				if (file_exists($old_res_pathfile)) {
					$result = unlink($old_res_pathfile);
					if ($result) $this->e("delete $old_res_pathfile error");
				}
			}
			//设置新的图片url
			$this->data_redis->hset("hu:{$this->uid}","avater_url",$data['avater_url']);
			$this->mysql->update("player",array("avater_url" => $data['avater_url']), array('id'=>$this->uid));
			$this->hander_coin_task_complete(1);//第一个任务是否完成		
			$this->returnData($data);
			
		}
		
		public function hander_coin_task_complete($task_id) {
			//从奖券任务记录字段中获取奖券任务完成度
			$task_complete_record_str = $this->data_redis->hget("hu:{$this->uid}","coin_task_complete_record");
			$task_pieces = explode("|", $task_complete_record_str);
			$task_value = $this->cache_redis->hget("hcointask:{$task_id}","task_value");
			//如果任务完成度 < 最大任务完成值,则任务完成度加1
			if ( (int)$task_pieces[$task_id - 1] < (int)$task_value)
			{
				$task_pieces[$task_id - 1] += 1;
			}
			else 
			{
				return;
			}
			
			//重新组装，任务奖励记录字符串
			$size = count($task_pieces);
			$str="";
			for ($i=0; $i<$size; $i++)
			{
				$str .= $task_pieces[$i];
				if ($i < $size-1)
				{
					$str .= "|";
				}
			}
			//重新设置任务奖励记录字符串
			$this->data_redis->hset("hu:{$this->uid}","coin_task_complete_record",$str);
			return;
		}
		
		
		public function after() {
			$this->deinitDataRedis();
			$this->deinitCacheRedis();
			$this->deinitMysql();
		}
		
		public function create_dir($dirName, $recursive = 1, $mode = 0777) {
			!is_dir($dirName) && mkdir($dirName, $mode, $recursive);
		}
    }
?>
